package com.elitetyc.customview.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Xfermode;
import android.location.OnNmeaMessageListener;
import android.util.AttributeSet;
import android.view.View;

import com.blankj.utilcode.util.ConvertUtils;
import com.elitetyc.customview.R;


/**
 * Created by elitetyc on 2019/5/22.
 * Describe:仿应用宝下载进度条
 */
public class YybProgressView extends View implements Runnable{

    private PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP);

//    默认的高度
    private int DEFAULT_HEIGHT_DP = 35;

//    边框圆角弧度
    private int radius;

//    边框宽度
    private int borderWidth;
//      文本大小
    private int textSize;
//    下载中的颜色，停止时的颜色
    private int loadingColor,stopColor;
// 文字画笔
    private Paint textPaint;
//    背景画笔
    private Paint bgPaint;
//    进度画笔
    private Paint pgPaint;
//     进度文字
    private String progressText;
//    文字矩形
    private Rect textRect;
    private RectF bgRectf;
//    背景bitmap
    private Bitmap pgBitmap;
    private Canvas pgCanvas;
//    滑块bitmap
    private Bitmap flikerBitmap;
//    滑块最左边的位置，作用是控制移动
    private float flikerLeft;
//  当前进度
    private float progress =0f;
//    最大进度值
    private float MAX_PROGRESS = 100f;
//    当前是否已经结束
    private boolean isFinish;
//    当前是否停止
    private boolean isStop;

//    进度文本，边框，进度条颜色
    private int progressColor;
    private Thread thread;
    private BitmapShader bitmapShader;

    public YybProgressView(Context context) {
        this(context,null);
    }

    public YybProgressView(Context context,  AttributeSet attrs) {
        this(context, attrs,0);
    }

    public YybProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
    }

//    获取自定义的属性
    private void initAttrs(AttributeSet attrs) {
        TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.YybProgressView);
        textSize = (int) array.getDimension(R.styleable.YybProgressView_textSize, ConvertUtils.dp2px(12));
        loadingColor = array.getColor(R.styleable.YybProgressView_loadingColor,Color.parseColor("#40c4ff"));
        stopColor = array.getColor(R.styleable.YybProgressView_stopColor,Color.parseColor("#ff9800"));
        radius = (int) array.getDimension(R.styleable.YybProgressView_radius,0);
        borderWidth = (int) array.getDimension(R.styleable.YybProgressView_borderWidth,1);
        array.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize= MeasureSpec.getSize(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        switch (heightMode){
//            atmost相当于wrap——content，这时候设置一个默认大小
            case MeasureSpec.AT_MOST:
                height =  ConvertUtils.dp2px(DEFAULT_HEIGHT_DP);
                break;
            case MeasureSpec.EXACTLY:
            case MeasureSpec.UNSPECIFIED:
                height = heightSize;
                break;
        }
        setMeasuredDimension(widthSize,height);
        if (pgBitmap==null) init();
    }

//    初始化画笔等等
    private void init(){
//        设置画笔抗锯齿，防抖动
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG|Paint.DITHER_FLAG);
//        设置时画空心图形
        bgPaint.setStyle(Paint.Style.STROKE);
//        设置画笔粗细
        bgPaint.setStrokeWidth(borderWidth);
        pgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        设置时填充画笔
        pgPaint.setStyle(Paint.Style.FILL);

        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(textSize);

        textRect = new Rect();
//        创建背景的显示区域，除开边框的宽度，要不然看不到边框
        bgRectf = new RectF(borderWidth,borderWidth,getMeasuredWidth()-borderWidth,getMeasuredHeight()-borderWidth);
//        根据是否停止展示不同的进度条颜色
        if (isStop){
            progressColor = stopColor;
        }else {
            progressColor = loadingColor;
        }
        flikerBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.flicker);
//        默认滑块一点都没显示，也就是左边在屏幕外
        flikerLeft = flikerBitmap.getWidth();

        initPgBitmap();


    }

//    初始化进度bitmap
    private void initPgBitmap() {
        pgBitmap = Bitmap.createBitmap(getMeasuredWidth()-borderWidth,getMeasuredHeight()-borderWidth,Bitmap.Config.ARGB_8888);
        pgCanvas = new Canvas(pgBitmap);
        thread = new Thread(this);
        thread.start();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        背景
        drawBackground(canvas);
//        画进度
        drawProgress(canvas);
//        画进度文字
        drawProgressText(canvas);
        //变色处理
        drawColorProgressText(canvas);
    }

    private void drawProgress(Canvas canvas) {
        pgPaint.setColor(progressColor);
//        当前进度的长度
        float left = (progress/MAX_PROGRESS)*getMeasuredWidth();
//        裁剪出当前进度下的bitmap长度
        pgCanvas.save();
        pgCanvas.clipRect(0,0,left,getMeasuredHeight());
        pgCanvas.drawColor(progressColor);
        pgCanvas.restore();

        if (!isStop){
            pgPaint.setXfermode(xfermode);
            pgCanvas.drawBitmap(flikerBitmap,flikerLeft,0,pgPaint);
            pgPaint.setXfermode(null);
        }


//        控制显示区域
        bitmapShader = new BitmapShader(pgBitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
        pgPaint.setShader(bitmapShader);
        canvas.drawRoundRect(bgRectf,radius,radius,pgPaint);

    }

    private void drawBackground(Canvas canvas) {
        bgPaint.setColor(progressColor);
//        画圆角矩形
        canvas.drawRoundRect(bgRectf,radius,radius,bgPaint);
    }

    /**
     * 进度提示文本
     * @param canvas
     */
    private void drawProgressText(Canvas canvas) {
        textPaint.setColor(progressColor);
        progressText = getProgressText();
        textPaint.getTextBounds(progressText, 0, progressText.length(), textRect);
        int tWidth = textRect.width();
        int tHeight = textRect.height();
        float xCoordinate = (getMeasuredWidth() - tWidth) / 2;
        float yCoordinate = (getMeasuredHeight() + tHeight) / 2;
        canvas.drawText(progressText, xCoordinate, yCoordinate, textPaint);
    }

    /**
     * 变色处理
     * @param canvas
     */
    private void drawColorProgressText(Canvas canvas) {
        textPaint.setColor(Color.WHITE);
        int tWidth = textRect.width();
        int tHeight = textRect.height();
        float xCoordinate = (getMeasuredWidth() - tWidth) / 2;
        float yCoordinate = (getMeasuredHeight() + tHeight) / 2;
        float progressWidth = (progress / MAX_PROGRESS) * getMeasuredWidth();
        if(progressWidth > xCoordinate){
            canvas.save();
            float right = Math.min(progressWidth, xCoordinate + tWidth * 1.1f);
            canvas.clipRect(xCoordinate, 0, right, getMeasuredHeight());
            canvas.drawText(progressText, xCoordinate, yCoordinate, textPaint);
            canvas.restore();
        }
    }

    private String getProgressText() {
        String text= "";
        if(!isFinish){
            if(!isStop){
                text = "下载中" + progress + "%";
            } else {
                text = "继续";
            }
        } else{
            text = "下载完成";
        }

        return text;
    }


    public void setProgress(float progress){
        if(!isStop){
            if(progress < MAX_PROGRESS){
                this.progress = progress;
            } else {
                this.progress = MAX_PROGRESS;
                finishLoad();
            }
            invalidate();
        }
    }

    public void setStop(boolean stop) {
        isStop = stop;
        if(isStop){
            progressColor = stopColor;
            thread.interrupt();
        } else {
            progressColor = loadingColor;
            thread = new Thread(this);
            thread.start();
        }
        invalidate();
    }

    public void finishLoad() {
        isFinish = true;
        setStop(true);
    }

    /**
     * 重置
     */
    public void reset(){
        setStop(true);
        progress = 0;
        isFinish = false;
        isStop = false;
        progressColor = loadingColor;
        progressText = "";
        flikerLeft = -flikerBitmap.getWidth();
        initPgBitmap();
    }

    public float getProgress() {
        return progress;
    }

    public boolean isStop() {
        return isStop;
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void toggle(){
        if(!isFinish){
            if(isStop){
                setStop(false);
            } else {
                setStop(true);
            }
        }
    }



    @Override
    public void run() {

        int width = flikerBitmap.getWidth();
        try {
            while (!isStop && !thread.isInterrupted()){
                flikerLeft += ConvertUtils.dp2px(5);
                float progressWidth = (progress / MAX_PROGRESS) * getMeasuredWidth();
                if(flikerLeft >= progressWidth){
                    flikerLeft = -width;
                }
                postInvalidate();
                Thread.sleep(20);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
